<?php
/**
 * OAuth登录客户端
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Controller
 * @link http://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */
 namespace ea\controller\index;

 use yesf\library\ControllerAbstract;
 use ea\model\Token;
 use ea\model\UserOAuth;
 use ea\model\OAuthClient as OAuthClientModel;
 use ea\model\Config;

class Oauthclient extends ControllerAbstract {
	//跳转
	public static function goAction($request, $response) {
		$response->disableView();
		$clientName = ucfirst($request->get['type']);
		$config = OAuthClientModel::get($clientName);
		if ($config === NULL || $config['enable'] === 0) {
			$response->status(404);
			$response->write('Not Found');
			return;
		}
		//初始化
		$client = OAuthClientModel::getClassName($clientName);
		if (!class_exists($client)) {
			$response->status(404);
			$response->write('Not Found');
			return;
		}
		$client::set($config);
		$response->assign('url', $client::getAuthorizeURL(Config::getInstance()->read('base_url') . 'oauthclient/callback/' . $name));
		$response->assign('default', Config::getInstance()->read('default_redirect'));
		$response->display('oauthclient/go');
	}
	//回调
	public static function callbackAction($request, $response) {
		$clientName = ucfirst($request->param['type']);
		$config = OAuthClientModel::get($clientName);
		if ($config === NULL || $config['enable'] === 0) {
			$response->status(404);
			$response->write('Not Found');
			return;
		}
		//初始化
		$client = OAuthClientModel::getClassName($clientName);
		if (!class_exists($client)) {
			$response->status(404);
			$response->write('Not Found');
			return;
		}
		$client::set($config);
		$code = $request->get['code'];
		//获取信息
		$token = $client::getAccessToken($code, self::getCallbackURL($request->header['host'], $clientName));
		$info = $client::getMyInfo($token['access_token']);
		//检查是否已经有绑定账号
		$user = UserOAuth::get([
			'openid' => $user['id'],
			'appid' => $client::ID
		]);
		if (is_array($user)) {
			$binded = TRUE;
			//自动登录
			list($token, $tverify) = Token::add($user['uid']);
			Authority::setLoginCookie($response, '_none_', '_none_', TRUE);
		} else {
			$binded = FALSE;
		}
		$response->assign('binded', $binded ? 1 : 0);
		$response->assign('default', Config::getInstance()->read('default_redirect'));
		if ($binded) {
			$response->assign('url', '');
			$response->assign('id', '');
			$response->assign('name', '');
			$response->assign('info', '');
			$response->assign('appid', $client::ID);
		} else {
			$response->assign('url', Config::getInstance()->read('oauth_redirect'));
			$response->assign('id', $info['id']);
			$response->assign('name', $info['name']);
			$response->assign('appid', $client::ID);
			$response->assign('info', OAuthClientModel::encrypt(array_merge(
				$token, $info, [
					'appid' => $client::ID
				])));
		}
		$response->display('oauthclient/callback');
	}
}
